package de.uni.muenster.idw2.xml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;
import de.uni.muenster.idw2.data.BoundingBox;

public class BBXMLParser {
	
	private String responeString;
	
	public BoundingBox getBuildings(HttpResponse response){
		responeString = request(response);
		BBXMLHandler bbxmlHandler = new BBXMLHandler();
		parse(bbxmlHandler);
		return bbxmlHandler.getBBBuildings();
	}
	
	private void parse (BBXMLHandler bbxmlHandler){
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			
			XMLReader xr = sp.getXMLReader();
			
			xr.setContentHandler(bbxmlHandler);
			
			
			InputSource inStream = new InputSource();
	        inStream.setCharacterStream(new StringReader(responeString));
			xr.parse(inStream);
			
		} catch (MalformedURLException e) {
			Log.e("wichtig", e.toString());
		} catch (ParserConfigurationException e) {
			Log.e("wichtig", e.toString());
		} catch (SAXException e) {
			Log.e("wichtig", e.toString());
		} catch (IOException e) {
			Log.e("wichtig", e.toString());
		}
	}
	
	public static String request(HttpResponse response){
        String result = "";
        try{
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                str.append(line);
            }
            in.close();
            result = str.toString();
        }catch(Exception ex){
            result = "Error";
        }
        return result;
    }

}
